package hw.txtreader;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;

import com.bifan.txtreaderlib.main.TxtConfig;
import com.bifan.txtreaderlib.ui.HwTxtPlayActivity;

import java.io.File;

import hw.txtreader.bean.Constant;
import hw.txtreader.fragment.FirstFragment;
import hw.txtreader.fragment.ForthFragment;
import hw.txtreader.fragment.SecondFragment;
import hw.txtreader.fragment.ThirdFragment;

import static hw.txtreader.bean.Constant.THIRD_TAG;

public class DemoActivity extends AppCompatActivity implements RadioGroup.OnCheckedChangeListener {
    private String tag = "MainActivity";
    private static final int MY_PERMISSIONS_REQUEST_WRITE_EXTERNAL_STORAGE = 0x01;
    private String FilePath = Environment.getExternalStorageDirectory() + "/test4.txt";
    private Boolean Permit = false;
    private long exitTime;
    private EditText mEditText;
    private FirstFragment firstFragment;
    private SecondFragment secondFragment;
    private ThirdFragment thirdFragment;
    private ForthFragment forthFragment;
    private RadioGroup radioGroup;//切换按钮的容器
    private RadioButton sport_btn, find_btn, heart_btn, mine_btn;//切换按钮

    FragmentManager manager;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mEditText = (EditText) findViewById(R.id.editText);
        mEditText.setText(FilePath);
        if (CheckPermission()) {
            Permit = true;
        } else {

        }
        //获取管理
        manager = getSupportFragmentManager();
        radioGroup = (RadioGroup) findViewById(R.id.ui_btn_group);
        sport_btn = (RadioButton) findViewById(R.id.sport_btn);
        find_btn = (RadioButton) findViewById(R.id.find_btn);
        heart_btn = (RadioButton) findViewById(R.id.heart_btn);
        mine_btn = (RadioButton) findViewById(R.id.mine_btn);
        firstFragment = new FirstFragment();
        secondFragment = new SecondFragment();
        thirdFragment = new ThirdFragment();
        forthFragment = new ForthFragment();
        if (radioGroup != null) {
            radioGroup.setOnCheckedChangeListener(this);
        }
        selectFragment(0);
        sport_btn.setChecked(true);
    }

    private void selectFragment(int index) {
        //每次切换都要获取一个新的事务
        FragmentTransaction transaction = manager.beginTransaction();
        switch (index) {
            case 0:
                transaction.replace(R.id.frag_home, firstFragment);
                break;
            case 1:
                transaction.replace(R.id.frag_home, secondFragment);
                break;
            case 2:
                transaction.replace(R.id.frag_home, thirdFragment);
                break;
            case 3:
                transaction.replace(R.id.frag_home, forthFragment);
                break;
                default:
        }
        //提交事务
        transaction.commit();
    }



    /**
     * 按两次退出按钮退出程序
     */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
            // System.currentTimeMillis()无论何时调用，肯定大于2000
            if ((System.currentTimeMillis() - exitTime) > 2000) {
                Toast.makeText(this, "再按一次退出程序", Toast.LENGTH_SHORT).show();
                exitTime = System.currentTimeMillis();
            } else {
                finish();
                System.exit(0);
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        ThirdFragment thirdFragment = (ThirdFragment) getSupportFragmentManager().findFragmentByTag(THIRD_TAG);
        thirdFragment.onActivityResult(requestCode,resultCode,data);
    }

    public void chooseFile(View view) {
        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
        intent.setType("text/plain");//设置类型
        intent.addCategory(Intent.CATEGORY_OPENABLE);
        startActivityForResult(intent, 3);
    }

    public void loadFile(View view) {
        if (Permit) {
            TxtConfig.saveIsOnVerticalPageMode(this, false);
            FilePath = mEditText.getText().toString().trim();
            if (TextUtils.isEmpty(FilePath) || !(new File(FilePath)).exists()) {
                toast("文件不存在");
            } else {
                HwTxtPlayActivity.loadTxtFile(this, FilePath);
            }
        }
    }

    public void onVerticalMode(View view) {
        if (Permit) {
            FilePath = mEditText.getText().toString().trim();
            if (TextUtils.isEmpty(FilePath) || !(new File(FilePath)).exists()) {
                toast("文件不存在");
            } else {
                TxtConfig.saveIsOnVerticalPageMode(this, true);
                HwTxtPlayActivity.loadTxtFile(this, FilePath);
            }
        }
    }


    public void loadStr(View view) {
        if (Permit) {
            String str = mEditText.getText().toString();
            if (TextUtils.isEmpty(str)) {
                toast("输入为空字符");
            } else {
                HwTxtPlayActivity.loadStr(this, str);
            }
        }
    }


    public void displayMore(View view) {
        if (Permit) {
            FilePath = mEditText.getText().toString().trim();
            if (TextUtils.isEmpty(FilePath) || !(new File(FilePath)).exists()) {
                toast("文件不存在");
            } else {
                Intent intent = new Intent(this, MoreDisplayActivity.class);
                intent.putExtra("filePath", FilePath);
                startActivity(intent);
            }
        }
    }

    private Boolean CheckPermission() {
        if (ContextCompat.checkSelfPermission(this,
                Manifest.permission.WRITE_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED) {

            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                    MY_PERMISSIONS_REQUEST_WRITE_EXTERNAL_STORAGE);
            return false;
        }
        return true;
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {

        if (requestCode == MY_PERMISSIONS_REQUEST_WRITE_EXTERNAL_STORAGE) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                Permit = true;
                loadFile(null);
            } else {
                // Permission Denied
                Toast.makeText(DemoActivity.this, "Permission Denied", Toast.LENGTH_SHORT).show();
            }
            return;
        }
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

    private Toast t;

    private void toast(String msg) {
        if (t != null) {
            t.cancel();
        }
        t = Toast.makeText(this, msg, Toast.LENGTH_SHORT);
        t.show();
    }


    @Override
    public void onPointerCaptureChanged(boolean hasCapture) {


    }

    @Override
    public void onCheckedChanged(RadioGroup group, int checkedId) {
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        switch (checkedId) {
            case R.id.sport_btn://运动
                if (!firstFragment.isAdded()) {
                    Bundle bundle = new Bundle();
                    bundle.putBoolean("is_launch", false);
                    firstFragment.setArguments(bundle);
                    transaction.replace(R.id.frag_home, firstFragment, Constant.FRIST_TAG);
                }
                break;
            case R.id.find_btn://发现
                if (!secondFragment.isAdded()) {
                    transaction.replace(R.id.frag_home, secondFragment, Constant.SECOND_TAG);
                }
                break;
            case R.id.heart_btn://心率
                if (!thirdFragment.isAdded()) {
                    transaction.replace(R.id.frag_home, thirdFragment, THIRD_TAG);
                }
                break;
            case R.id.mine_btn://我的
                if (!forthFragment.isAdded()) {
                    transaction.replace(R.id.frag_home, forthFragment, Constant.FORTH_TAG);
                }
                break;
            default:
                break;
        }
        transaction.commit();
    }
}
